package com.example.service.impl;

import com.example.entity.Category;
import com.example.entity.CategoryExample;
import com.example.entity.Ebook;
import com.example.mapper.CategoryMapper;
import com.example.req.CategorySaveReq;
import com.example.service.CategoryService;
import com.example.utils.CopyUtil;
import com.example.utils.SnowFlake;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Iterator;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    SnowFlake snowFlake;


    @Override
    public List<Category> findCategory() {

        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        return categoryMapper.selectByExample(categoryExample);
    }

    @Override
    public void saveCategory(final CategorySaveReq req) {
        Category category = CopyUtil.copy(req, Category.class);

        if(ObjectUtils.isEmpty(category.getId())){

            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);

        }else{
            categoryMapper.updateByPrimaryKey(category);
        }
    }

    @Override
    public void deleteCategory(final Long id) {
        categoryMapper.deleteByPrimaryKey(id);
    }

}
